package org.merak.core.web.mvc.validation;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.merak.core.model.ProgrammaticException;

public final class TemplateParameter {

	//~ Constants ////////////////////////////////////////////////////////////////
	//****************************************************************************
	public static final Pattern PATTERN = Pattern.compile(
			"([^{}]+)(\\{([0-9]+)(,([0-9]+))?})?"
	);

	//~ Attributes ///////////////////////////////////////////////////////////////
	//****************************************************************************
	private final String name;
	private final long   minLength;
	private final long   maxLength;

	//~ Constructors /////////////////////////////////////////////////////////////
	//****************************************************************************
	public TemplateParameter(String name,long minLength,long maxLength) {

		this.name      = name;
		this.minLength = minLength;
		this.maxLength = maxLength;

	}
	//****************************************************************************
	public TemplateParameter(String template) {

		// Parse parameter names and bounds
		Matcher matcher = PATTERN.matcher(template);
		if (matcher.find()) {
			this.name      = matcher.group(1);
			this.minLength = (matcher.group(3) == null) ? 0   : Long.parseLong(matcher.group(3));
			this.maxLength = (matcher.group(5) == null) ? 256 : Long.parseLong(matcher.group(5));
		}
		else throw new ProgrammaticException(
			"Syntax Error: parameter definition '" + template + "' must match " +
			"<name>{<minLengh>,<maxLength>}, where <name> accepts any character"
		);

	}

	//~ Methods //////////////////////////////////////////////////////////////////
	//****************************************************************************
	public final String getName() {
		return this.name;
	}
	//****************************************************************************
	public final long getMaxLength() {
		return this.maxLength;
	}
	//****************************************************************************
	public final long getMinLength() {
		return this.minLength;
	}
	//****************************************************************************
	@Override
	public String toString() {
		return this.name;
	}
	//****************************************************************************


}
